//
//  UIImage+ClipImage.m
//  HDChuZhou
//
//  Created by mac on 2017/5/24.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "UIImage+ClipImage.h"

@implementation UIImage (ClipImage)

+ (UIImage *)imageFromImage:(UIImage *)image inRect:(CGRect)rect {
    CGSize imageSize = image.size;
    CGRect finalRect = [UIImage getRectFrommageSize:imageSize WithImageViewRect:rect.size];
    
    CGImageRef sourceImageRef = [image CGImage];
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, finalRect);
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    CGImageRelease(newImageRef);
    return newImage;
}

+ (CGRect)getRectFrommageSize:(CGSize)imageSize WithImageViewRect:(CGSize)viewSize{
    
    CGRect rect;
    CGFloat w;
    CGFloat h;
    CGFloat scale = viewSize.width/viewSize.height;
    
    if (imageSize.height >= imageSize.width) {
        
        w = imageSize.width;
        h = imageSize.width/scale;
        
        if (h>imageSize.height) {
            CGFloat sca = h/imageSize.height;
            w = w/sca;
            h = h/sca;
        }
        
    }else{
        h = imageSize.height;
        w = imageSize.height*scale;
        
        if (w>imageSize.width) {
            CGFloat sca = w/imageSize.width;
            w = w/sca;
            h = h/sca;
        }
    }
    
    rect = CGRectMake((imageSize.width-w)/2.0, (imageSize.height-h)/2.0, w, h);
    return rect;
}


@end
